import { defineStore } from 'pinia'
import {reqLogin, reqLogout, reqUserInfo} from "@/api/user";
import {userState} from "@/store/modules/types/types";
import {TOKEN_GET, TOKEN_SET} from "@/utils/token";
import {constRoutes} from "@/router/routes";
import {RouteRecordRaw} from "vue-router";
import type {loginFormData, loginResponseDataType, userInfoResponseDataType} from '@/api/user/type'

let useUserStore = defineStore('User', {
    state: (): userState => {
        return {
            token: TOKEN_GET(),
            menuRouters: constRoutes as RouteRecordRaw[],
            username: '',
            avatar: ''
        }
    },
    actions: {
        // 用户登录
        async userLogin(userInfo: loginFormData){
            const res: loginResponseDataType = await reqLogin(userInfo)
            if (res.code === 200) {
                // 登录成功
                TOKEN_SET((res.data as String))
                this.token = (res.data as String)
                return 'ok'
            } else {
                // 登录失败
                return Promise.reject(new Error(res.data as String))
            }
        },
        // 获取用户信息
        async getUserInfo() {
            const res: userInfoResponseDataType = await reqUserInfo()
            if (res.code === 200) {
                this.username = res.data.name
                this.avatar = res.data.avatar
                return 'OK'
            } else {
                return Promise.reject(new Error(res.message))
            }
        },
        // 退出登录
        async logout(){
            const res: any = await reqLogout()
            if (res.code === 200) {
                this.token = ''
                this.username = ''
                this.avatar = ''
                localStorage.removeItem('token')
                return 'OK'
            } else {
                return Promise.reject(new Error(res.message))
            }
        }

    },
    getters: {}
})

export default useUserStore
